<template>
  <BasicModal
    v-bind="$attrs"
    destroyOnClose
    @register="registerModal"
    showFooter
    :title="titleName"
    width="40rem"
    @ok="handleSubmit"
    @cancel="cancel"
  >
    <div style="padding-left: 4px" v-if="treeData">
      <Alert
        class="custom-ant-alert-info"
        :closable="true"
        message="修改权限后，请角色相关用户重新登录起效。"
        show-icon
      />
      <!-- <div v-if="hanldeType == 1" class="menu-title">菜单权限设置</div> -->

      <BasicTree
        v-model:checkedKeys="checkeds"
        :fieldNames="{ key: 'id', title: 'name' }"
        :treeData="treeData"
        :checkable="true"
        defaultExpandLevel="1"
      />

      <!-- <p v-if="hanldeType == 1" class="menu-title">导航权限设置</p> -->
      <!-- <BasicTree
        v-if="hanldeType == 1"
        v-model:checkedKeys="checkedNavs"
        :fieldNames="{ key: 'id', title: 'name' }"
        :treeData="treeAppNav"
        :checkable="true"
        defaultExpandLevel="1"
      /> -->
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, nextTick } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Alert } from 'ant-design-vue';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { getModulesRoleListApi, updateModulesRoleApi } from '/@/api/admin/menu';

  export default defineComponent({
    name: 'RoleAuth',
    components: { BasicModal, BasicTree, Alert },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      let titleList: string[] = ['菜单权限', 'APP菜单权限'];
      let titleName = ref<string>('');

      const updateId = ref();
      const { createMessage } = useMessage();
      const treeData = ref<TreeItem[]>();
      const checkeds = ref<string[]>([]);
      const checkedNavs = ref<string[]>([]);
      let hanldeType = ref(0);
      let treeAppNav = ref<TreeItem[]>([]);
      // let treeAppMenu: TreeItem[] = [];
      // type ExtractKeys = {
      //   appMenu: string[];
      //   appNav: string[];
      // };
      // const extractCheckKeys = (
      //   keys: string[],
      //   k1: TreeItem[],
      //   k2: TreeItem[],
      // ): Object<ExtractKeys> => {
      //   let menuKeyList = k1.map((i) => i.id);
      //   let navKeyList = k2.map((i) => i.id);
      //   let appMenu: string[] = [];
      //   let appNav: string[] = [];
      //   keys.forEach((i) => {
      //     if (menuKeyList.includes(i)) {
      //       appMenu.push(i);
      //     }
      //     if (navKeyList.includes(i)) {
      //       appNav.push(i);
      //     }
      //   });
      //   return {
      //     appMenu,
      //     appNav,
      //   };
      // };
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        setModalProps({ confirmLoading: true });
        updateId.value = data?.record.roleId;
        hanldeType.value = data.record.hanldeType;
        titleName.value = titleList[hanldeType.value];
        let { tree, checkedKeys } = await getModulesRoleListApi({
          roleId: updateId.value,
          client: hanldeType.value,
        });

        // if (hanldeType.value == 1) {
        //   treeAppNav.value = tree.filter((i) => i.menuType === 2);
        //   treeAppMenu = tree.filter((i) => i.menuType === 0);

        //   treeData.value = treeAppMenu;
        //   const keys = extractCheckKeys(checkedKeys, treeAppMenu, treeAppNav.value);

        //   nextTick(() => {
        //     checkeds.value = keys.appMenu;
        //     checkedNavs.value = keys.appNav;
        //   });
        // } else {
        //   treeData.value = tree;
        //   nextTick(() => {
        //     checkeds.value = checkedKeys;
        //   });
        // }
        treeData.value = tree;
        nextTick(() => {
          checkeds.value = checkedKeys;
        });
        setModalProps({ confirmLoading: false });
      });

      // async function getModulesRoleList(roleId) {
      //   const res = await getModulesRoleListApi({ roleId });
      //   return { ...res };
      // }

      async function handleSubmit() {
        console.log(checkeds.value);

        try {
          setModalProps({ confirmLoading: true });

          await updateModulesRoleApi({
            roleId: updateId.value,
            params: {
              checkedKeys: checkeds.value,
              client: hanldeType.value,
            },
          });
          closeModal();

          createMessage.success('操作成功');
          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      const cancel = () => {
        treeData.value = [];
      };
      //复选框 点击
      const handleTreeNode = (_, node) => {
        console.log(node);
      };

      return {
        cancel,
        registerModal,
        handleSubmit,
        treeData,
        checkeds,
        titleName,
        hanldeType,
        treeAppNav,
        checkedNavs,
        handleTreeNode,
      };
    },
  });
</script>
<style scoped lang="less">
  :deep(.custom-ant-alert-info.custom-ant-alert-info) {
    background-color: rgba(43, 99, 161, 0.08) !important;
  }

  .menu-title {
    font-weight: bold;
    margin-top: 20px;
  }
</style>
